package org.grayrabbit.cloud.core.biz;

import org.grayrabbit.cloud.core.application.BizApplication;
import org.grayrabbit.cloud.core.config.Configurator;
import org.grayrabbit.cloud.core.config.ConfiguratorException;
import org.grayrabbit.cloud.core.module.ModuleException;
import org.grayrabbit.cloud.core.module.NoSuchModuleException;
import org.grayrabbit.cloud.core.rpc.Argument;
import org.grayrabbit.cloud.core.rpc.ChannelFactory;
import org.grayrabbit.cloud.core.rpc.LocalChannelFactory;
import org.grayrabbit.cloud.core.rpc.LocalServerFactory;
import org.grayrabbit.cloud.core.rpc.Result;
import org.grayrabbit.cloud.core.rpc.ServerFactory;

public class BizUtility {

	private static Configurator serverContext;
	private static BizApplication serverApplication;
	private static Configurator clientContext;
	private static BizApplication clientApplication;
	//禁用工具化进行实例会
	private BizUtility(){		
	}
	public static void initialize(BizApplication bizApplication,boolean server) {
		if(server){
			serverApplication = bizApplication;
			serverContext = bizApplication.getConfigurator();
		}else{
			clientApplication = bizApplication;
			clientContext = bizApplication.getConfigurator();
		}
	}

	public static String getProperty(String category, String name,
			String property,boolean server) throws ConfiguratorException {
		if(server){
			String value = serverContext.getProperty(category, name, property);
			if (value == null)
			throw new ConfiguratorException(
			String.format("Missing property:{%s::%s::%s}", new Object[] { category, name, property }));
			return value;
		}else{
			String value = clientContext.getProperty(category, name, property);
			if (value == null)
			throw new ConfiguratorException(
			String.format("Missing property:{%s::%s::%s}", new Object[] { category, name, property }));
			return value;
		}
	}
	
	public static BizModule getModule(String name,boolean server) throws NoSuchModuleException
	{
		if(server)
			return (BizModule)serverApplication.get(name);
		else
			return (BizModule)clientApplication.get(name);
	}
	public static void removeModule(String name, BizModule module,boolean server) {
		if(server)
			serverApplication.remove(name, module);
		else
			clientApplication.remove(name, module);
	}

	public static ServerFactory getServerFactory() {
		return new LocalServerFactory();
	}
	
	

	public static Result submit(String module, Argument argument,boolean server) throws NoSuchModuleException, ModuleException {
		return getModule(module,server).submit(argument);
	}

	public static ChannelFactory<Result> getChannelFactory() {
		return new LocalChannelFactory();
	}

}
